/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.web.client;

import java.util.ArrayList;
import java.util.List;

import com.cleangwt.json.client.SimpleObject;
import com.cleangwt.web.shared.PagedResult;
import com.cleangwt.web.shared.PagedResultDeserializer;
import com.google.gwt.user.cellview.client.AbstractCellTable;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;

/**
 * The {@link AsyncDataProvider} for remote paging.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class RemotePagingProvider extends AsyncDataProvider<SimpleObject> {

  private final String target;
  private AbstractCellTable<SimpleObject> table;
  private ProvidesCriteria criteriaProvider;

  private boolean displayInitialzied;

  /**
   * Creates a remote data provider with the specified target.
   * 
   * @param target the remote target to fetch data.
   */
  public RemotePagingProvider(String target) {
    assert target != null : "The target must not be null.";
    this.target = target;
  }

  /**
   * Sets the criteria provider.
   * 
   * @param criteriaProvider the {@link CriteriaProvider}
   */
  public void setCriteriaProvider(ProvidesCriteria criteriaProvider) {
    this.criteriaProvider = criteriaProvider;
  }

  /**
   * Fetches data from remote.
   */
  public void fetch() {
    assert table != null : "You hava not display, call #addDataDisplay() first.";
    if (!displayInitialzied) {
      displayInitialzied = true;
      super.addDataDisplay(table);
      table.addColumnSortHandler(new ColumnSortEvent.AsyncHandler(table));
    } else {
      table.setVisibleRangeAndClearData(new Range(0, table.getPageSize()), true);
    }
  }

  @Override
  public void addDataDisplay(HasData<SimpleObject> display) {
    assert table == null : "The #addDataDisplay may only be called once.";
    this.table = (AbstractCellTable<SimpleObject>) display;
    // add display when #fetch() once called, here just set row count 0 to
    // hide the loading indicator.
    this.table.setRowCount(0);
  }

  @Override
  protected void onRangeChanged(HasData<SimpleObject> display) {
    SimpleObject criteria = criteriaProvider.getCriteria();
    SimpleObject pc = new SimpleObject();
    ColumnSortList sortList = table.getColumnSortList();
    pc.put("criteria", criteria);
    pc.put("pageStart", table.getVisibleRange().getStart());
    pc.put("pageSize", table.getPageSize());

    if (sortList != null && sortList.size() > 0) {
      List<String> sortedColumns = new ArrayList<String>();
      List<String> sortedDirections = new ArrayList<String>();
      for (int i = 0; i < sortList.size(); i++) {
        sortedColumns.add(sortList.get(i).getColumn().getDataStoreName());
        sortedDirections.add(sortList.get(i).isAscending() ? "asc" : "desc");
      }

      pc.put("sortedColumns", sortedColumns);
      pc.put("sortedDirections", sortedDirections);
    }

    Requests.postObject(target, pc, new StatedCallback() {

      @Override
      protected void onSuccess(String result) {
        PagedResult pagedResult = PagedResultDeserializer.get().deserialize(result);

        List<SimpleObject> list = pagedResult.getPageList();
        long count = pagedResult.getAvailableCount();
        if (count == 0) {
          table.setRowCount(0);
        } else {
          table.setRowCount((int) count, false);
          updateRowData(table.getVisibleRange().getStart(), list);
        }
      }

    });
  }

}
